package com.dd.controller;

import com.dd.model.Product;
import com.dd.service.ProductService;
import com.dd.util.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 商品控制器
 */
@RestController
@RequestMapping("/products")
public class ProductController {
    
    private static final Logger logger = LoggerFactory.getLogger(ProductController.class);
    
    @Autowired
    private ProductService productService;
    
    @Autowired
    private RedisUtil redisUtil;
    
    @Value("${redis.enabled}")
    private boolean redisEnabled;
    
    /**
     * 获取所有商品
     */
    @GetMapping
    public ResponseEntity<List<Product>> getAllProducts() {
        List<Product> products = productService.findAllProducts();
        return ResponseEntity.ok(products);
    }
    
    /**
     * 根据ID获取商品
     */
    @GetMapping("/{id}")
    public ResponseEntity<?> getProduct(@PathVariable("id") Integer id) {
        Product product = productService.getProductById(id);
        if (product == null) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "商品不存在");
            return ResponseEntity.badRequest().body(response);
        }
        return ResponseEntity.ok(product);
    }
    
    /**
     * 根据分类查询商品
     */
    @GetMapping("/category/{category}")
    public ResponseEntity<List<Product>> getProductsByCategory(@PathVariable("category") String category) {
        List<Product> products = productService.findProductsByCategory(category);
        return ResponseEntity.ok(products);
    }
    
    /**
     * 根据名称查询商品
     */
    @GetMapping("/search")
    public ResponseEntity<List<Product>> searchProducts(@RequestParam("name") String name) {
        List<Product> products = productService.findProductsByName(name);
        return ResponseEntity.ok(products);
    }
    
    /**
     * 添加商品
     */
    @PostMapping
    public ResponseEntity<Map<String, Object>> addProduct(@RequestBody Product product) {
        Map<String, Object> response = new HashMap<>();
        boolean result = productService.addProduct(product);
        
        if (result) {
            response.put("success", true);
            response.put("message", "添加商品成功");
            response.put("productId", product.getProductId());
        } else {
            response.put("success", false);
            response.put("message", "添加商品失败");
        }
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 更新商品
     */
    @PutMapping("/{id}")
    public ResponseEntity<Map<String, Object>> updateProduct(@PathVariable("id") Integer id, 
                                                             @RequestBody Product product) {
        Map<String, Object> response = new HashMap<>();
        
        // 设置ID
        product.setProductId(id);
        
        boolean result = productService.updateProduct(product);
        
        if (result) {
            response.put("success", true);
            response.put("message", "更新商品成功");
        } else {
            response.put("success", false);
            response.put("message", "更新商品失败，商品可能不存在");
        }
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 删除商品
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> deleteProduct(@PathVariable("id") Integer id) {
        Map<String, Object> response = new HashMap<>();
        boolean result = productService.deleteProduct(id);
        
        if (result) {
            response.put("success", true);
            response.put("message", "删除商品成功");
        } else {
            response.put("success", false);
            response.put("message", "删除商品失败，商品可能不存在");
        }
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 更新商品库存
     */
    @PutMapping("/{id}/stock/{stock}")
    public ResponseEntity<Map<String, Object>> updateProductStock(@PathVariable("id") Integer id,
                                                                  @PathVariable("stock") Integer stock) {
        Map<String, Object> response = new HashMap<>();
        boolean result = productService.updateProductStock(id, stock);
        
        if (result) {
            response.put("success", true);
            response.put("message", "更新商品库存成功");
        } else {
            response.put("success", false);
            response.put("message", "更新商品库存失败，商品可能不存在");
        }
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 清除商品缓存
     */
    @GetMapping("/cache/clear")
    public ResponseEntity<Map<String, Object>> clearProductCache() {
        Map<String, Object> response = new HashMap<>();
        
        // 检查Redis是否启用
        if (!redisEnabled) {
            logger.info("Redis缓存未启用，无需清除缓存");
            response.put("success", true);
            response.put("message", "Redis缓存未启用，无需清除缓存");
            return ResponseEntity.ok(response);
        }
        
        try {
            // 清除所有以product:开头的缓存
            Set<String> keys = redisUtil.keys("product:*");
            
            if (keys == null || keys.isEmpty()) {
                logger.info("没有找到需要清除的商品缓存");
                response.put("success", true);
                response.put("message", "没有找到需要清除的商品缓存");
                response.put("count", 0);
                return ResponseEntity.ok(response);
            }
            
            long count = redisUtil.delete(keys);
            
            logger.info("已清除{}个商品缓存", count);
            
            response.put("success", true);
            response.put("message", "清除商品缓存成功，共清除" + count + "个缓存项");
            response.put("count", count);
        } catch (Exception e) {
            logger.error("清除商品缓存失败", e);
            response.put("success", false);
            response.put("message", "清除商品缓存失败: " + e.getMessage());
        }
        
        return ResponseEntity.ok(response);
    }
}